# -*- coding: utf-8 -*-
# File : init_sys_env.py
# Author: taoyahui
# Date : 2021/6/17
from fabric import Connection
import logging
import re
from utils import random_util, log_util, common_util
import results
import time
import os

logging.basicConfig(level=logging.INFO)


# 获取系统初始化信息
def get_init_sys_env(ip, username, passwd, port):
    c = Connection(f"{username}@{ip}", connect_kwargs={'password': passwd})
    try:
        res = c.run('lsb_release -a')
        out_list = res.stdout.split('\n')
        os_value = 'Linux'
        for str in out_list:
            if 'Description' in str:
                os_value = str.split('\t')[-1]

        return os_value
    except Exception as e:
        logging.log(logging.INFO, f"{ip} can't find os ,try another way")
    try:
        res = c.run('cat /etc/redhat-release')
        return res.stdout
    except Exception as e:
        logging.log(logging.INFO, f'{ip} is not Redhat Series')
    finally:
        c.close()


# 获取主机的HOSTNAME
def init_hostname(ip, username, passwd, port):
    c = Connection(f"{username}@{ip}", connect_kwargs={'password': passwd})
    try:
        res = c.run('hostname')
        if res.stdout.strip() == 'localhost.localdomain':
            new_hostname = 'test' + random_util.random_string()
            c.run(f'hostnamectl --static set-hostname {new_hostname}')
            return new_hostname
        else:
            res = c.run('hostname')
            return res.stdout.strip()
    except Exception as e:
        logging.log(logging.ERROR, e)
    finally:
        c.close()


def sync_remote_source(ip, username, passwd, port):
    """
    设置资产的远程源
    :param ip:
    :param username:
    :param passwd:
    :param port:
    :return:
    """

    c = Connection(f"{username}@{ip}", port=port, connect_kwargs={'password': passwd})
    try:
        log_util.logger.info(f"开始执行远程数据源切换操作, IP: {ip}")
        root_path = common_util.get_root_dir()
        c.run('rm -rf /etc/yum.repos.d.bak')
        c.run('mv /etc/yum.repos.d /etc/yum.repos.d.bak')
        time.sleep(0.5)
        c.run('mkdir -p /etc/yum.repos.d')
        c.put(os.path.join(root_path, 'scripts', 'ftp.repo'), '/etc/yum.repos.d')


    except Exception as e:
        log_util.logger.info(f"同步资产远程源失败,IP : {ip}, 错误原因: {e}")
        return results.inventory_remote_source_sync_error
    try:
        res = c.run('yum clean all')
        print(res.stdout)
        time.sleep(1)
        res = c.run('yum makecache')
        print(res.stdout)
    except Exception as e:
        log_util.logger.info(f"同步资产远程源失败,IP : {ip}, 错误原因: {e}")
        return results.inventory_remote_source_sync_error
    finally:
        c.close()


if __name__ == '__main__':
    # print(get_init_sys_env('192.168.50.199', 'root', '123456', 22))
    sync_remote_source('192.168.50.144', 'root', '123456', 22)
    pass
